import 'dart:convert';
import 'dart:io';
import 'package:broadcast_events/broadcast_events.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import '../../modules/login/bindings/login_binding.dart';
import '../../modules/login/views/login_view.dart';
import '../networking/http_manager.dart';
import '../widget/my_dialog.dart';
import 'const.dart';

const String baseURL = "https://echelianapi.ygxpt.com";
const String baseURLTest = "http://222.222.17.184:8990";

// ignore: non_constant_identifier_names
final local_hosts = {
  "http://192.168.0.49:70": "孙亚琪",
  "http://192.168.0.xx:xx": "王森",
  "http://192.168.0.x:xxx": "史宇航",
};

class AppManager {
  // 单例
  // AppManager._share();
  // static final AppManager _instance = AppManager._share();
  // static AppManager get instance { return _instance;}
  static String uuid = ""; // 设备唯一标识
  static String device = ""; // 设备型号, 例如: iPhone
  static String userToken = "";
  static String deviceBrand = ""; // 设备型号, 例如: 华为、苹果、小米
  static String deviceModel = ""; // 设备型号, 例如: iPhone 15
  static String appName = ""; //
  static String version = ""; // app version
  static String buildNumber = ""; // app buildNumber
  static bool isPhysicalDevice = false; // 是否是真机(物理设备)
  static bool isFirstInstall = true; // 默认第一次安装
  //static bool auth = false; // 生物认证状态，在 App 重启后会失效
  static UserAccount? user; // 当前登录账号
  static String? lastAccount;  // 上次登录账号,退出登录后userData删除,但该值依旧存在
  static ShopModel? currentShop; // 当前店铺
  static ImageProvider? launchImage; // app启动图

  // static ActiveAdvertModel? activeAdvert;
  // static PopupAdvertModel? popAdvert;

  static bool isShowUpload = false; // 记录更新提示的弹出框，避免重复叠加弹框。



  // 注册通知
  static registerBroadcast(String name, Function(dynamic value) result) {
    BroadcastEvents().subscribe(name, result);
  }

  // 删除通知
  static deleteBroadcast(String name) {
    BroadcastEvents().unsubscribe(name);
  }

  // 发送通知
  static sendBroadcast(String name, {dynamic value}) {
    BroadcastEvents().publish(name, arguments: value);
  }

  // 获取上次登录的用户信息
  static getUserData() {
    UserAccount? user = AppManager.getUserAccountModel();
    AppManager.user = user;


    // 获取上次选中的店铺
    ShopModel? shop = AppManager.getShopModel();
    AppManager.currentShop = shop;

    // 获取上次登录的账号
    AppManager.lastAccount = localStorageRead("lastAccount");

    debugPrint("getUserData() 执行完毕!");
    debugPrint("上次登录的用户 = ${AppManager.lastAccount}");
    debugPrint("AppManager.userAccount = ${AppManager.user}");
    debugPrint("AppManager.currentShop = ${AppManager.currentShop}");
  }

  // 获取认证状态
  static getAuthState() {
    final auth = localStorageRead("native_auth") ?? false;
    debugPrint("getAuthState() 执行完毕！ 认证状态：$auth");
    return auth;
  }

  // 获取设备信息
  static getDeviceInfo() async {
    final DeviceInfoPlugin device = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await device.androidInfo;
      AppManager.deviceModel = androidInfo.model;
      // 这是一个设备特定的64位标识符，在Android设备首次启动时生成。每次设备恢复出厂设置时，ID会重置。
      // 在Android 8.0及更高版本中，对于每个新的应用安装，此标识符都是不同的。
      AppManager.uuid = androidInfo.id;
      AppManager.deviceBrand = androidInfo.brand;
      AppManager.isPhysicalDevice = androidInfo.isPhysicalDevice;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await device.iosInfo;
      AppManager.device = iosInfo.model.toString();
      AppManager.deviceBrand = "Apple";
      AppManager.deviceModel = getIphoneModel(iosInfo.utsname.machine);
      AppManager.uuid = iosInfo.identifierForVendor!;
      AppManager.isPhysicalDevice = iosInfo.isPhysicalDevice;
    }
    debugPrint("getDeviceInfo() 执行完毕！");
    debugPrint("AppManager.device = ${AppManager.device}");
    debugPrint("AppManager.deviceName = ${AppManager.deviceModel}");
    debugPrint("AppManager.uuid = ${AppManager.uuid}");
    debugPrint("AppManager.deviceBrand = ${AppManager.deviceBrand}");
    debugPrint("AppManager.isPhysicalDevice = ${AppManager.isPhysicalDevice}");

    // 获取 app 版本信息
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    AppManager.version = packageInfo.version;
    AppManager.appName = packageInfo.appName;
    AppManager.buildNumber = packageInfo.buildNumber;
    debugPrint("appName: ${packageInfo.appName} version: ${packageInfo.version} (${packageInfo.buildNumber})");
    debugPrint("packageName = ${packageInfo.packageName}");
  }

  // 退出登录
  static signOut() {
    AppManager.user = null;
    AppManager.currentShop = null;
    AppManager.clearUserAccount();
    AppManager.clearShopModel();
    Get.offAll(()=> const LoginView(), binding: LoginBinding(), transition: Transition.noTransition);
  }

  static Future<void> deleteDirectory(FileSystemEntity file) async {
    // PermissionStatus status = await Permission.storage.status;
    if (file is Directory && file.existsSync()) {
      debugPrint(file.path);
      final List<FileSystemEntity> children =
      file.listSync(recursive: true, followLinks: true);
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
      }
    }
    try {
      if (file.existsSync()) {
        await file.delete(recursive: true);
      }
    } catch (err) {
      // debugPrint(err);
    }
  }

  //循环获取缓存大小
  static Future getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    //  File
    if (file is File && file.existsSync()) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory && file.existsSync()) {
      List children = file.listSync();
      double total = 0;
      if (children.isNotEmpty)
        // ignore: curly_braces_in_flow_control_structures
        for (final FileSystemEntity child in children) {
          total += await getTotalSizeOfFilesInDir(child);
        }
      return total;
    }
    return 0;
  }

  /// 获取缓存
  static Future<String> findCacheSumSize() async {
    final tempDir = await getTemporaryDirectory();
    double cache = await AppManager.getTotalSizeOfFilesInDir(tempDir);
    return formatSize(cache);
  }

  /// 删除缓存
  static Future clearApplicationCache() async {
    final tempDir = await getTemporaryDirectory();
    showLoadingMessage("清除中...");
    await AppManager.deleteDirectory(tempDir);
    dismissLoading();
    showMessage("清除成功");
  }

  /// 缓存大小格式转换
  static String formatSize(double value) {
    // ignore: unnecessary_null_comparison
    if (value == null) {
      return '0';
    }
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

// ===============================================================================
//                      本地用户信息模型
// ===============================================================================
  static setUserAccountJson(Map<String, dynamic> user) {
    AppManager.user = UserAccount.fromJson(user);
    AppManager.lastAccount = AppManager.user!.loginName!;
    localStorageWrite(kUserAccountUpdate, jsonEncode(user));
    localStorageWrite("lastAccount", AppManager.user?.loginName!);
  }
  static Future<Map<String, dynamic>> getUserAccountJson() async {
    var string = await localStorageRead(kUserAccountUpdate);
    return jsonDecode(string!);
  }
  static UserAccount? getUserAccountModel() {
    var string = localStorageRead(kUserAccountUpdate);
    if (string != null) {
      return UserAccount.fromJson(jsonDecode(string!));
    }
    return null;
  }
  static clearUserAccount() async {
    await localStorageRemove(kUserAccountUpdate);
  }

// ===============================================================================
//                       本地保存商店模型
// ===============================================================================
  static setShopModel(ShopModel shop) {
    AppManager.currentShop = shop;
    final sid = AppManager.currentShop?.shopId;
    Map<String, dynamic> baseParam = {"shopInfoId": sid, "shopId": sid};
    HttpManager.setBaseParam(baseParam);
    debugPrint("HttpManager.baseParam = $baseParam");
    localStorageWrite(kStoreChange, jsonEncode(shop.toJson()));
  }
  static ShopModel? getShopModel() {
    var string = localStorageRead(kStoreChange);
    if (string != null) {
      return ShopModel.fromJson(jsonDecode(string!));
    }
    return null;
  }
  static clearShopModel() async {
    await localStorageRemove(kStoreChange);
  }

  static getDeviceToken() async {
    // return await UmengPushManager.getDeviceToken();
  }



}

// ===============================================================================
//                AppManager 常用模型
// ===============================================================================
class UserAccount {
  String? loginName;
  String? password;
  String? userToken;
  UserAccount({this.loginName, this.password, this.userToken});
  factory UserAccount.fromJson(Map<String, dynamic> json) {
    return UserAccount(
      loginName: json['loginName'],
      password: json['password'],
      userToken: json['userToken'],
    );
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['loginName'] = loginName;
    data['password'] = password;
    data['userToken'] = userToken;
    return data;
  }
}

class ShopModel {
  String? shopName;
  String? shopId;
  ShopModel({this.shopName, this.shopId});
  factory ShopModel.fromJson(Map<String, dynamic> json) {
    return ShopModel(
      shopName: json['shopName'],
      shopId: json['shopId'],
    );
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['shopName'] = shopName;
    data['shopId'] = shopId;
    return data;
  }
}

// ===============================================================================
//                                    本地存储
// ===============================================================================
GetStorage box = GetStorage();
localStorageWrite(String key, dynamic value) async {
  await box.write(key, value);
}
T? localStorageRead<T>(String key) {
  return box.read(key);
}
localStorageRemove(String key) async {
  await box.remove(key);
}
// ===============================================================================
//                                    本地存储
// ===============================================================================



// ===============================================================================
//                       获取 iOS 设备型号名称
// ===============================================================================
String getIphoneModel(String machine) {
  return _iOSModels[machine] ?? machine;
}
const _iOSModels = {
  "i386": "iPhone Simulator",
  "x86_64": "iPhone Simulator",
  "iPhone1,1": "iPhone 2G",
  "iPhone1,2": "iPhone 3G",
  "iPhone2,1": "iPhone 3GS",
  "iPhone3,1": "iPhone 4",
  "iPhone3,2": "iPhone 4",
  "iPhone3,3": "iPhone 4",
  "iPhone4,1": "iPhone 4S",
  "iPhone5,1": "iPhone 5",
  "iPhone5,2": "iPhone 5",
  "iPhone5,3": "iPhone 5C",
  "iPhone5,4": "iPhone 5C",
  "iPhone6,1": "iPhone 5S",
  "iPhone6,2": "iPhone 5S",
  "iPhone7,2": "iPhone 6",
  "iPhone7,1": "iPhone 6 Plus",
  "iPhone8,1": "iPhone 6S",
  "iPhone8,2": "iPhone 6S Plus",
  "iPhone8,4": "iPhone SE (1st generation)",
  "iPhone9,1": "iPhone 7",
  "iPhone9,3": "iPhone 7",
  "iPhone9,2": "iPhone 7 Plus",
  "iPhone9,4": "iPhone 7 Plus",
  "iPhone10,1": "iPhone 8",
  "iPhone10,4": "iPhone 8",
  "iPhone10,2": "iPhone 8 Plus",
  "iPhone10,5": "iPhone 8 Plus",
  "iPhone10,3": "iPhone X",
  "iPhone10,6": "iPhone X",
  "iPhone11,8": "iPhone XR",
  "iPhone11,2": "iPhone XS",
  "iPhone11,6": "iPhone XS Max",
  "iPhone11,4": "iPhone XS Max",
  "iPhone12,1": "iPhone 11",
  "iPhone12,3": "iPhone 11 Pro",
  "iPhone12,5": "iPhone 11 Pro Max",
  "iPhone12,8": "iPhone SE (2nd generation)",
  "iPhone13,1": "iPhone 12 mini",
  "iPhone13,2": "iPhone 12",
  "iPhone13,3": "iPhone 12 Pro",
  "iPhone13,4": "iPhone 12 Pro Max",
  "iPhone14,4": "iPhone 13 mini",
  "iPhone14,5": "iPhone 13",
  "iPhone14,2": "iPhone 13 Pro",
  "iPhone14,3": "iPhone 13 Pro Max",
  "iPhone14,6": "iPhone SE (3rd generation)",
  "iPhone14,7": "iPhone 14",
  "iPhone14,8": "iPhone 14 Plus",
  "iPhone15,2": "iPhone 14 Pro",
  "iPhone15,3": "iPhone 14 Pro Max",
  "iPhone15,4": "iPhone 15",
  "iPhone15,5": "iPhone 15 Plus",
  "iPhone15,6": "iPhone 15 Pro",
  "iPhone15,7": "iPhone 15 Pro Max",

  "iPad1,1": "iPad 1",
  "iPad2,1": "iPad 2",
  "iPad2,2": "iPad 2",
  "iPad2,3": "iPad 2",
  "iPad2,4": "iPad 2",
  "iPad3,1": "iPad 3",
  "iPad3,2": "iPad 3",
  "iPad3,3": "iPad 3",
  "iPad3,4": "iPad 4",
  "iPad3,5": "iPad 4",
  "iPad3,6": "iPad 4",
  "iPad4,1": "iPad Air",
  "iPad4,2": "iPad Air",
  "iPad4,3": "iPad Air",
  "iPad5,3": "iPad Air 2",
  "iPad5,4": "iPad Air 2",
  "iPad6,7": "iPad Pro 12.9-inch",
  "iPad6,8": "iPad Pro 12.9-inch",
  "iPad6,3": "iPad Pro 9.7-inch",
  "iPad6,4": "iPad Pro 9.7-inch",
  "iPad6,11": "iPad 5th generation",
  "iPad6,12": "iPad 5th generation",
  "iPad7,1": "iPad Pro 12.9-inch 2nd generation",
  "iPad7,2": "iPad Pro 12.9-inch 2nd generation",
  "iPad7,3": "iPad Pro 10.5-inch",
  "iPad7,4": "iPad Pro 10.5-inch",
  "iPad7,5": "iPad 6th generation",
  "iPad7,6": "iPad 6th generation",
  "iPad7,11": "iPad 7th generation",
  "iPad7,12": "iPad 7th generation",
  "iPad8,1": "iPad Pro 11-inch",
  "iPad8,2": "iPad Pro 11-inch",
  "iPad8,3": "iPad Pro 11-inch",
  "iPad8,4": "iPad Pro 11-inch",
  "iPad8,5": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,6": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,7": "iPad Pro 12.9-inch 3rd generation",
  "iPad8,8": "iPad Pro 12.9-inch 3rd generation",
  "iPad11,1": "iPad mini 5th generation",
  "iPad11,2": "iPad mini 5th generation",
  "iPad11,3": "iPad Air 3rd generation",
  "iPad11,4": "iPad Air 3rd generation",
  "iPad11,6": "iPad 8th generation",
  "iPad11,7": "iPad 8th generation",
  "iPad12,1": "iPad 9th generation",
  "iPad12,2": "iPad 9th generation",
  "iPad13,1": "iPad Air 4th generation",
  "iPad13,2": "iPad Air 4th generation",
  "iPad13,4": "iPad Pro 11-inch 3rd generation",
  "iPad13,5": "iPad Pro 11-inch 3rd generation",
  "iPad13,6": "iPad Pro 11-inch 3rd generation",
  "iPad13,7": "iPad Pro 11-inch 3rd generation",
  "iPad13,8": "iPad Pro 12.9-inch 5th generation",
  "iPad13,9": "iPad Pro 12.9-inch 5th generation",
  "iPad13,10": "iPad Pro 12.9-inch 5th generation",
  "iPad13,11": "iPad Pro 12.9-inch 5th generation",
  "iPad14,1": "iPad mini 6th generation",
  "iPad14,2": "iPad mini 6th generation",
  "iPad14,3": "iPad Pro 11-inch 4th generation",
  "iPad14,4": "iPad Pro 11-inch 4th generation",
  "iPad14,5": "iPad Pro 12.9-inch 6th generation",
  "iPad14,6": "iPad Pro 12.9-inch 6th generation",
};



